﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Data.Schema.Sql.SchemaModel;
using Microsoft.Data.Schema.SchemaModel;

namespace TFDP.Common
{
    public static class ColumnExtensions
    {
        /// <summary>
        /// Obtain the type of the current column instance
        /// </summary>
        /// <param name="column">The current instance</param>
        /// <returns>The type as a string</returns>
        public static string GetSqlType(this ISqlColumn column)
        {
            if (column == null)
                throw new ArgumentNullException("column");

            if (column is ISqlComputedColumn)
            {
                try
                {
                    return column.GetExtendedProperty<string>("computedColumnType") ?? String.Empty;
                }
                catch
                {
                    return String.Empty;
                }
            }

            if (column.TypeSpecifier == null)
                return String.Empty;
            if (column.TypeSpecifier.Type != null)
            {
                if (column.TypeSpecifier.Length == 0 && column.TypeSpecifier.Precision != 0)
                {
                    return String.Format(
                           "{0}({1},{2})",
                           column.TypeSpecifier.Type.Name.Parts.Last(),
                           column.TypeSpecifier.Precision,
                           column.TypeSpecifier.Scale
                       );
                }
                else
                {
                    return String.Format(
                        "{0}{1}",
                        column.TypeSpecifier.Type.Name.Parts.Last(),
                        column.TypeSpecifier.Length != 0 ? "(" + column.TypeSpecifier.Length + ")" : ""
                    );
                }
            }
            else
                return column.TypeSpecifier.PrimarySource.Script;
        }

        /// <summary>
        /// Format the NULL/NOT NULL/default string for the given column
        /// </summary>
        /// <param name="column">The column to format</param>
        /// <returns></returns>
        public static string ColumnNullSpec(this ISqlColumn column)
        {
            ModelPropertyClass propertyClass = column.ElementClass.GetPropertyClass("IsNullable");
            if (propertyClass == null)
                return "NULL";

            bool isNullable = column.GetProperty<bool>(propertyClass);

            if (isNullable)
                return "NULL";
            else
                return "NOT NULL";
        }
    }
}
